<?php
class DomBankLinkController extends DomController {
	
	public function index() {
		$this->initLinks();
		
		if( $_POST ) {
			DomBankPayment::getTable()->update();
			$payment = DomBankPayment::createNew( $_POST['price'], $_POST['description'], $_POST['bank'] );
			$payment->sendToBank();
		}
		
		$view = new DomView('DomBankLink/send.html');
		$view->banks = DomBankLink::getLinks();
		$panel = array(
			'title' => 'Send to bank form',
			'html' => $view->fetch(),
		);
				
		$this->view->contents = DomFg::render( $panel );
		
		
	}
	
	public function handleCallBack( $bank ) {
		$this->initLinks();
		
		$replay = DomBankPayment::handleReplay( $bank );
	
		$str = '<a href="'.$this->getUrl().'">Make another payment</a>';
		if( $replay->status == DomBankPayment::OK) {
			
			if( $replay->handled ) {
				// User refreshed or something like this. (This is not failure)
				$str .= '<h3 style="color:orange">Payment already processed!</h3>';
			
			} else {
				$replay->finished();
				
				// add money to user account or buy etc...
				
				$str .= '<h3 style="color:green">Successful payment</h3>';
			}
			
			// show successful payment message
			
		} elseif( $replay->status == DomBankPayment::CANCEL ) {
		 	
			$str .= '<h3 style="color:red">User cancelled payment!</h3>';

		} else {
			$str .= '<h3 style="color:red">Error: '.$replay->status.'</h3>';
		}	
	
		$str .= '<b>Payment info</b><br>';
		$str .= 'PaymentId: <b>'.$replay->id.'</b><br>';
		$str .= 'Price: <b style="color:red">'.$replay->price.' '.strtoupper($replay->currency).'</b><br>';
		$str .= 'Client account: <b>'.$replay->clientAccountNr.'</b><br>';
		$str .= 'Client name: <b>'.$replay->clientName.'</b><br>';
		$str .= 'Profile: <b>'.$replay->profile.'</b><br>';
		$str .= 'Bank: <b>'.$replay->bank.'</b><br>';
		$str .= 'Payment description: <b>'.$replay->description.'</b><br>';
		
		
		$panel = array(
			'title' => 'Back from bank',
			'bodyStyle' => 'padding:10px; line-height:1.5em; text-align:center;',
			'html' => $str,
		);
		
		$this->view->contents = DomFg::render( $panel );
	}
	
	public function log() {
					
		$source = new DomArDataSource( DomBankPayment::dataQuery()->select('t.*')->orderBy('t.sendTime DESC'), 40 );
		
		function price( $row ) {
			return $row['price'].' '.strtoupper($row['currency']);
		}
		
		function status( $row ) {
			if( $row['status'] == DomBankPayment::OK ) {
				return '<b style="color:green">OK</b>';
			} else if( $row['status'] == DomBankPayment::CANCEL ) {
				return '<b style="color:orange">Cancelled</b>';
			} else {
				return '<b style="color:red">ERROR</b>';
			}
		}
		
		$totalPayments = DomSql::selectOneQuery('SELECT count(*) as n FROM '.DomBankPayment::getDbTable().'','n');
		$successfulPayments = DomSql::selectOneQuery('SELECT count(*) as n, SUM(price) as s FROM '.DomBankPayment::getDbTable().' WHERE status=\''.DomBankPayment::OK.'\' LIMIT 1');
		$successfulPaymentsSum = $successfulPayments['s'];
		$successfulPayments = $successfulPayments['n'];
		$cancelledPayments = DomSql::selectOneQuery('SELECT count(*) as n FROM '.DomBankPayment::getDbTable().' WHERE status=\''.DomBankPayment::CANCEL.'\'','n');
		$didntComeBackPayments = DomSql::selectOneQuery('SELECT count(*) as n FROM '.DomBankPayment::getDbTable().' WHERE status=\''.DomBankPayment::SENT_TO_BANK.'\'','n');
		$erroredPayments = DomSql::selectOneQuery('SELECT count(*) as n FROM '.DomBankPayment::getDbTable().' WHERE status=\''.DomBankPayment::ERROR.'\'','n');
		
		
		$panel = array(
			'title' => 'Payments',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 6,
				'columnWidths' => array(150,140,200,100,150),
			),
			'items' => array(
				array(
					'type' => 'value',
					'title' => 'Total payments',
					'value' => '<b style="color:blue">'.$totalPayments.'</b>',
				),
				array(
					'type' => 'value',
					'title' => 'Didn\'t come back from bank',
					'value' => '<b style="color:orange">'.$didntComeBackPayments.'</b>',
				),
				array(
					'type' => 'value',
					'title' => 'Errored payments',
					'value' => '<b style="color:red">'.$erroredPayments.'</b>',
				),
				array(
					'type' => 'value',
					'title' => 'Successful payments',
					'value' => '<b style="color:green">'.$successfulPayments .' ('.number_format($successfulPaymentsSum,2,'.',' ').' EEK)'.'</b>',
				),
				array(
					'type' => 'value',
					'title' => 'Cancelled payments',
					'value' => '<b style="color:orange">'.$cancelledPayments.'</b>',
					'colspan' => 3,
				),
				array(
					'type' => 'grid',
					'source' => $source,
					'colspan' => 6,
					'fields' => array(
						array('key' => 'id', 'title' => 'ID', 'width'=>40),
						array('key' => 'sendIp', 'title' => 'IP', 'width'=>100),
						array('key' => 'sendTime', 'title' => 'Datetime', 'width'=>150),
						array('handler' => 'price', 'title' => 'Price', 'width'=>100),
						array('key' => 'profile', 'title' => 'Profile', 'width'=>100),
						array('handler' => 'status', 'title' => 'Status', 'width'=>100),
						array('key' => 'clientName', 'title' => 'Name', 'width'=>120),
						array('key' => 'description', 'title' => 'Description'),
					),
				),
			),
		);
					
		$this->view->contents = DomFg::render( $panel );
		
		
	}
	
	private function initLinks() {
		
		DomBankLink_Dummy::c('dummy')
			->privateKey('adsfk0340adsföSD')
			->defaultCallbackUrl( $this->getUrl('handleCallBack/dummy/') );
		
		DomBankLink_Swed::c('swed')
			->privateKey('')
			->requestKey('')
			->resellerId('')
			->resellerAccount('')
			->resellerName('')
			->serverUrl('https://www.swedbank.ee/banklink')
			->defaultCallbackUrl( $this->getUrl('handleCallBack/swed/') );
		
		DomBankLink_Seb::c('seb')
			->privateKey('')
			->requestKey('')
			->resellerId('')
			->resellerAccount('')
			->resellerName('')
			->serverUrl('https://www.seb.ee/cgi-bin/unet3.sh/un3min.r')
			->defaultCallbackUrl( $this->getUrl('handleCallBack/seb/') );
			
		DomBankLink_Sampo::c('sampo')
			->privateKey('')
			->requestKey('')
			->resellerId('')
			->resellerAccount('')
			->resellerName('')
			->serverUrl('https://www2.sampopank.ee/ibank/pizza/pizza')
			->defaultCallbackUrl( $this->getUrl('handleCallBack/seb/') );
		
		DomBankLink_Paypal::c('paypal')
           	->resellerAccount('')
           	->authToken('')
           	->serverUrl('https://www.paypal.com/cgi-bin/webscr')
			->defaultCallbackUrl( $this->getUrl('handleIdentifyCallBack/paypal/') );
	}
		
	
	public function identify() {
		$this->initIdentifyLinks();
		
		if( $_POST ) {
			DomBankIdentify::getTable()->update();
			$payment = DomBankIdentify::createNew( $_POST['bank'] );
			$payment->sendToBank();
		}
		
		$view = new DomView('DomBankLink/identify.html');
		$view->banks = DomBankLink::getLinks();
		$panel = array(
			'title' => 'Send to bank form',
			'html' => $view->fetch(),
		);
				
		$this->view->contents = DomFg::render( $panel );
		
	}
	
	public function handleIdentifyCallBack( $bank, $id ) {
		$this->initIdentifyLinks();
		$replay = DomBankIdentify::handleReplay( $bank, $id );
	
		$str = '<a href="'.$this->getUrl('identify').'">Identify again</a>';
		if( $replay->status == DomBankIdentify::OK) {
			
			if( $replay->handled ) {
				// User refreshed or something like this. (This is not failure)
				$str .= '<h3 style="color:orange">Identify already processed!</h3>';
			
			} else {
				$replay->finished();
				
				// add money to user account or buy etc...
				
				$str .= '<h3 style="color:green">Successful identify</h3>';
			}
			
			// show successful payment message
			
		} elseif( $replay->status == DomBankIdentify::CANCEL ) {
		 	
			$str .= '<h3 style="color:red">User cancelled!</h3>';

		} else {
			$str .= '<h3 style="color:red">Error: '.$replay->status.'</h3>';
		}	
	
		$str .= '<b>Payment info</b><br>';
		$str .= 'PaymentId: <b>'.$replay->id.'</b><br>';
		$str .= 'Person code: <b>'.$replay->clientCode.'</b><br>';
		$str .= 'Person name: <b>'.$replay->clientName.'</b><br>';
		$str .= 'Profile: <b>'.$replay->profile.'</b><br>';
		$str .= 'Bank: <b>'.$replay->bank.'</b><br>';
		
		
		$panel = array(
			'title' => 'Back from bank',
			'bodyStyle' => 'padding:10px; line-height:1.5em; text-align:center;',
			'html' => $str,
		);
		
		$this->view->contents = DomFg::render( $panel );
	}
	
	private function initIdentifyLinks() {
		
		DomBankLink_Dummy::c('dummy')
			->privateKey('adsfk0340adsföSD')
			->defaultCallbackUrl( $this->getUrl('handleIdentifyCallBack/dummy/') );
		
		DomBankLink_Swed::c('swed')
			->privateKey('')
			->requestKey('')
			->resellerId('')
			->resellerAccount('')
			->resellerName('')
			->serverUrl('https://www.swedbank.ee/banklink')
			->defaultCallbackUrl( $this->getUrl('handleIdentifyCallBack/swed/') );
		
		DomBankLink_Seb::c('seb')
			->privateKey('')
			->requestKey('')
			->resellerId('')
			->resellerAccount('')
			->resellerName('')
			->serverUrl('https://www.seb.ee/cgi-bin/unet3.sh/un3min.r')
			->defaultCallbackUrl( $this->getUrl('handleIdentifyCallBack/seb/') );
			
		DomBankLink_Sampo::c('sampo')
			->privateKey('')
			->requestKey('')
			->resellerId('')
			->resellerAccount('')
			->resellerName('')
			->serverUrl('https://www2.sampopank.ee/ibank/pizza/pizza')
			->defaultCallbackUrl( $this->getUrl('handleIdentifyCallBack/sampo/') );
			
		DomBankLink_IdCard::c('idCard')
			->defaultCallbackUrl( $this->getUrl('handleIdentifyCallBack/idCard/') );
	}
	
	
	public function settingUp() {
		$view = new DomView('DomBankLink/description.html');
		$view->banks = DomBankLink::getLinks();
		$panel = array(
			'title' => 'Creating certs',
			'bodyStyle' => 'padding:10px',
			'html' => $view->fetch(),
		);
				
		$this->view->contents = DomFg::render( $panel );
	}

}
?>